package com.example.demo.dao.daoimpl;

import com.example.demo.dao.UserDao;
import com.example.demo.entity.User;
import com.example.demo.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;


import java.util.List;

public class UserDaoImpl implements UserDao {
    @Override
    public User selectUserByMessage(String account, String password) {
        Session session= HibernateUtil.openSession();
        Transaction tx=session.beginTransaction();
        String hql="from User u where u.account=?1 and u.password=?2";
        List<User> list=session.createQuery(hql, User.class).setParameter(1,account).setParameter(2,password).list();
        tx.commit();
        HibernateUtil.closeSession();
        return list.size()>0?list.get(0):null;
    }

    @Override
    public void saveUser(String account, String password) {
        Session session= HibernateUtil.openSession();
        Transaction tx=session.beginTransaction();
        User user=new User(account,password);
        System.out.println(user);
        session.save(user);
        tx.commit();
        HibernateUtil.closeSession();
    }

    @Override
    public User selectUserByAccount(String account) {
        Session session= HibernateUtil.openSession();
        Transaction tx=session.beginTransaction();
        String hql="from User u where u.account=?1";
        List<User> list=session.createQuery(hql, User.class).setParameter(1,account).list();
        tx.commit();
        HibernateUtil.closeSession();
        return list.size()>0?list.get(0):null;
    }

    @Override
    public void editUser(User user) {
        Session session= HibernateUtil.openSession();
        Transaction tx=session.beginTransaction();
        session.update(user);
        tx.commit();
        HibernateUtil.closeSession();
    }

    @Override
    public void uploadPassword(User user) {
        Session session= HibernateUtil.openSession();
        Transaction tx=session.beginTransaction();
        session.update(user);
        tx.commit();
        HibernateUtil.closeSession();
    }

}
